package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.vo.ExportProductVo;
import cn.itcast.vo.ExportResult;
import cn.itcast.vo.ExportVo;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.BeanMapUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.sql.DataSource;
import java.io.InputStream;
import java.util.*;

@Controller
@RequestMapping("/cargo/export")
@Slf4j
public class PdfController extends BaseController {

    /**
     * 导出PDF （1） 入门案例
     * http://localhost:8080/cargo/export/exportPdf.do?id=7
     */
    @RequestMapping("/exportPdf1")
    public void exportPdf1() throws Exception {
        // 加载jasper文件流
        InputStream in =
                super.httpSession.getServletContext().getResourceAsStream("/jasper/test01.jasper");

        // 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, new HashMap<>(), new JREmptyDataSource());

        // 导出pdf文件
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }

    /**
     * 导出PDF （2） map方式填充模板数据
     */
    @RequestMapping("/exportPdf2")
    public void exportPdf2() throws Exception {
        // 加载jasper文件流
        InputStream in =
                super.httpSession.getServletContext()
                        .getResourceAsStream("/jasper/test02_parameter.jasper");

        // 定义map，往模板中填充数据； map的key要与模板中的Parameters参数名称一致
        Map<String, Object> map = new HashMap<>();
        map.put("userName", "大娃");
        map.put("deptName", "应用开发部");
        map.put("email", "bigball@itcast.cn");
        map.put("companyName", "字节跳动");

        // 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, map, new JREmptyDataSource());

        // 导出pdf文件
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    // 注入连接池
    @Autowired
    private DataSource dataSource;

    /**
     * 导出PDF （4）数据源填充数据 A  JDBC数据源填充数据
     */
    @RequestMapping("/exportPdf4")
    public void exportPdf4() throws Exception {
        // 加载jasper文件流
        InputStream in =
                super.httpSession.getServletContext()
                        .getResourceAsStream("/jasper/test04_jdbc.jasper");

        // 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, null, dataSource.getConnection());

        // 导出pdf文件
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    /**
     * 导出PDF （5）数据源填充数据 B JavaBean数据源填充数据
     */
    @RequestMapping("/exportPdf5")
    public void exportPdf5() throws Exception {
        // 加载jasper文件流
        InputStream in =
                super.httpSession.getServletContext()
                        .getResourceAsStream("/jasper/test05_javabean.jasper");

        // 创建javabean对象，封装模板数据; 注意：map的key或者bean的属性要与Fields的名称一致
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 1; i < 6; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("userName", "大娃" + i);
            map.put("deptName", "应用开发部");
            map.put("email", "bigball@itcast.cn");
            map.put("companyName", "字节跳动");
            list.add(map);
        }

        // 创建数据源对象，封装集合数据
        JRDataSource dataSource = new JRBeanCollectionDataSource(list);

        // 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, null, dataSource);

        // 导出pdf文件
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    /**
     * 导出PDF （6）分组报表
     */
    @RequestMapping("/exportPdf6")
    public void exportPdf6() throws Exception {
        // 加载jasper文件流
        InputStream in =
                super.httpSession.getServletContext()
                        .getResourceAsStream("/jasper/test06_group.jasper");

        // 创建javabean对象，封装模板数据; 注意：map的key或者bean的属性要与Fields的名称一致
        List<Map<String, Object>> list = new ArrayList<>();
        for (int j = 1; j <= 2; j++) { // 企业
            for (int i = 1; i < 6; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("userName", "大娃" + i);
                map.put("deptName", "应用开发部");
                map.put("email", "bigball@itcast.cn");
                map.put("companyName", "字节跳动" + j);
                list.add(map);
            }
        }

        // 创建数据源对象，封装集合数据
        JRDataSource dataSource = new JRBeanCollectionDataSource(list);

        // 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, null, dataSource);

        // 导出pdf文件
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    /**
     * 导出PDF （7）图形报表
     */
    @RequestMapping("/exportPdf7")
    public void exportPdf7() throws Exception {
        // 加载jasper文件流
        InputStream in =
                super.httpSession.getServletContext()
                        .getResourceAsStream("/jasper/test07_chart.jasper");

        // map中的key就是统计指标；value就是统计指标的值，是Integer类型(匹配模板中fields字段的类型)
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 1; i < 6; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("title","安踏运动厂家"+i);
            map.put("value",new Random().nextInt(100));
            list.add(map);
        }

        // 创建数据源对象，封装集合数据
        JRDataSource dataSource = new JRBeanCollectionDataSource(list);

        // 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, null, dataSource);

        // 导出pdf文件
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;

    /**
     * 报运单详情导出
     */
    @RequestMapping("/exportPdf")
    public void exportPdf(String id) throws Exception {
        // 加载jasper文件流
        InputStream in =
                super.httpSession.getServletContext()
                        .getResourceAsStream("/jasper/export.jasper");

        //第一： 根据报运单id，查询报运单对象
        Export export = exportService.findById(id);
        // 对象--->map， 调用工具类把javabean对象转换为map集合
        Map<String, Object> map = BeanMapUtils.beanToMap(export);

        //第二： 根据报运单id，查询商品
        ExportProductExample example = new ExportProductExample();
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> list = exportProductService.findAll(example);

        // 创建数据源对象，封装集合数据
        JRDataSource dataSource = new JRBeanCollectionDataSource(list);

        // 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, map, dataSource);

        // 导出pdf文件
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-disposition","attachment;fileName=export.pdf");
        ServletOutputStream outputStream = response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
        outputStream.close();
    }



}